package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditImpl extends
        ServiceImpl<CarPackageAuditMapper,CarPackageAudit>implements ICarPackageAuditService {
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IServiceItemService serviceItemService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        CarPackageAudit carPackageAudit = this.getById(id);
        //获取流程图对象
        List<String> activeActivityIds=null;
        //如果状态为审核中或者审核拒绝，说明还正在流程中
        if (carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)){
            //获取实例对象
             activeActivityIds = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }else {
            activeActivityIds = new ArrayList<>();
        }
        //拿到bpmn对象
            BpmnInfo bpmnInfo = bpmnInfoService.getById(carPackageAudit.getBpmnInfoId());
            BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            return generator.generateDiagram(bpmnModel,activeActivityIds,Collections.EMPTY_LIST,"宋体","宋体","宋体");
        }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.getById(id);
        //设置为审核取消
        UpdateWrapper<CarPackageAudit>  carPackageWrapper=new UpdateWrapper<>();
        carPackageWrapper.eq("id",id);
        carPackageWrapper.set("status",CarPackageAudit.STATUS_CANCEL);
        //设置套餐初始化
        UpdateWrapper<ServiceItem> wrapper=new UpdateWrapper<>();
        wrapper.eq("id",audit.getServiceItemId());
        wrapper.set("sale_status",ServiceItem.AUDITSTATUS_INIT);
        serviceItemService.update(null,wrapper);
        //撤销实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"撤销审核");
    }

    @Override
    @Transactional
    public void audit(Long id, int auditStatus, String info) {
        //先判断状态
        CarPackageAudit carPackageAudit = this.getById(id);
        if(carPackageAudit==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("只有处于审核状态的记录才能进行审核操作");
        }
        //获取当前登录用户名
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            info = userName+"【同意】,批注意见:"+info;
        }else{
            info = userName+"【拒绝】,批注意见:"+info;
        }
        //设置备注意见
        carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+info);
        //获取当前节点
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
       //给审核流程设置通过还是拒绝的值 判断条件
        taskService.setVariable(currentTask.getId(),"auditStatus",auditStatus);
        //taskService.addComment(currentTask.getId(),carPackageAudit.getInstanceId(),info);
        //提交当前任务
        taskService.complete(currentTask.getId());
        //获取下一个节点
        //可以知道当前对象是结束了还是有下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            if(nextTask!=null){
                //财务审核
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                carPackageAudit.setAuditTime(new Date());
            }else{
                //审核通过
                //将养修套餐表审核状态修改成审核成功
                UpdateWrapper<ServiceItem> wrapper=new UpdateWrapper<>();
                wrapper.eq("id",carPackageAudit.getServiceItemId());
                wrapper.set("audit_status",ServiceItem.AUDITSTATUS_APPROVED);
                serviceItemService.update(null,wrapper);
                //将审核列表状态设置成审核通过
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        }else{
            //审核拒绝
            //将养修套餐表审核状态修改成审核初始化
            UpdateWrapper<ServiceItem> wrapper=new UpdateWrapper<>();
            wrapper.eq("id",carPackageAudit.getServiceItemId());
            wrapper.set("audit_status",ServiceItem.AUDITSTATUS_INIT);
            serviceItemService.update(null,wrapper);
           //将审核列表状态设置成审核拒绝
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
        }
        //审核结束 设置当前审核人为空
        carPackageAudit.setAuditorId(null);
        //更新审核列表
        UpdateWrapper<CarPackageAudit> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",carPackageAudit.getId()) ;
        this.updateById(carPackageAudit);
    }
}


